/*
 * This file defines the functions and data structures 
 * relating to calculating stats and parsing the batting.txt file
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NAME_LENGTH 20

// Structures

// Structure to simulate a cricket player
struct cricket_player{
	char name[NAME_LENGTH];
	char country[3]; // Contains a country code
	int innings;
	int runs;
	int times_not_out;
	int highest_score;
	int highest_score_is_not_out; // Boolean
};

// Method defenitions
struct cricket_player get_player(char player_name[]);

// Method declerations
struct cricket_player get_player(char player_name[]){
	FILE *file;
	char *mode = "rt";
	char outputFilename[] = "battings.txt";
	char delimiter = ';';

	struct cricket_player player;

	// Open the file
	file = fopen(outputFilename, mode);

	if (file == NULL) {
		fprintf(stderr, "Can't open output file %s!\n", outputFilename);
		exit(1);
	}

	// parse the file
  	int  buffer_size = 200;
  	char line_buffer[buffer_size];  
  	while( fgets(line_buffer, buffer_size, file) != NULL ){      
		if(line_buffer[0] == '#'){
			//printf("The character was # skip\n");
      	}
      	else{
			char name[NAME_LENGTH];
	
			// init name_buffer with null values TODO extract method
			int k;
			for(k = 0; k < NAME_LENGTH; k++){
	    		name[k] = '\0';
			}
	
			// find the player in question
			int i;
			int j = 0;
			for(i = 0; i < buffer_size; i++){
	  			char c = line_buffer[i];
	  
	  			if(c != delimiter){
	    			name[j] = c;
	    			j++;
	  			}else{ // Name has been found
	    			// Compare it to the recieved name
	    			if( strcmp(name, player_name) == 0 ){
	      				printf("Player found %s\n", name);
	      				
						//Init the cricket player
						char *ptr = line_buffer;
						char field [32];

						int n;
						int m = 1;
						while ( sscanf(ptr, "%31[^;]%n", field, &n) == 1 ){
							printf("field %d = \"%s\"\n", m, field);

							if(m == 1){ 
								int a;
								for(a = 0; a < strlen(field); a++)
									player.name[a] = field[a];							
							} 						
							else if(m == 2){ 
								int a;
								for(a = 0; a < strlen(field); a++)
									player.country[a] = field[a];							
							} 
							else if(m == 3) 
								player.innings = atoi(field);							
							else if(m == 4) 
								player.runs = atoi(field);							
							else if(m == 5) 
								player.times_not_out = atoi(field);							
							else if(m == 6) 
								player.highest_score = atoi(field);	
							else if(m == 7){
								if(strcmp(field, "TRUE"))
									player.highest_score_is_not_out = 1;
								else 
									player.highest_score_is_not_out = 0;
							}						
							m++;							
							ptr += n; 

							if ( *ptr != delimiter ){
								break; 
							}

							++ptr; 
	      				}
						player.runs = 10;
	    			}
    
	    			break;
	  			}
			}	  
		}
	}
    
  	//Close the file
  	fclose(file);

  	// return the player 
	return player;
}

/* Only for testing */
int main(void){
	char name[] = "Sarwan";

	struct cricket_player player;
	player = get_player(name);
	
	printf("Players name: %s\n", 						player.name);
	printf("Players country: %s\n", 					player.country);
	printf("Players innings: %d\n", 					player.innings);
	printf("Players runs: %d\n",	 					player.runs);
	printf("Players times_not_out: %d\n",				player.times_not_out);
	printf("Players highest_score: %d\n", 				player.highest_score);
	printf("Players highest_score_is_not_out: %d\n", 	player.highest_score_is_not_out);

	exit(EXIT_SUCCESS);
}

/*int main(void)
{
	const char line[] = "Adams;WI;10;151;2;49;FALSE";

	const char *ptr = line;

	char field [ 32 ];

	int n;

	while ( sscanf(ptr, "%31[^;]%n", field, &n) == 1 )

	{

		printf("field = \"%s\"\n", field);

		ptr += n; /* advance the pointer by the number of characters read */

		/*if ( *ptr != ';' )

		{

		break; /* didn't find an expected delimiter, done? */

	//}

	//++ptr; /* skip the delimiter */

	/*}

	return 0;
}*/


/*
Statistics::

Innings (I): The number of innings in which the batsman actually batted.

Not outs (NO): The number of times the batsman was not out at the conclusion of an innings they batted in.1

Runs (R): The number of runs scored.

Highest Score (HS/Best): The highest score ever made by the batsman.

Batting Average (Ave): The total number of runs divided by the total number of innings in which the batsman was out. Ave = Runs/[I - NO] (also Avge or Avg.)

Centuries (100): The number of innings in which the batsman scored one hundred runs or more.

Half-centuries (50): The number of innings in which the batsman scored fifty to ninety-nine runs (centuries do not count as half-centuries as well).

Balls Faced (BF): The total number of balls received, including no balls but not including wides.

Strike Rate (SR): The number of runs scored per 100 balls faced. (SR = [100 * Runs]/BF)

 

1 Batsmen who are not required to bat in a particular innings (due to victory or declaration) are not considered "Not Out" in that innings. 
Only the player/s who have taken to the crease and remained there until the completion of an innings, are marked "Not Out" on the scorecard.

For statistical purposes, batsmen who retire due to injury or illness are also deemed not out [1], while batsmen who retire for any other 
reason are deemed out [2], except in exceptional circumstances (in 1983 Gordon Greenidge, not out on 154, departed a Test match to be with 
his daughter, who was ill and subsequently died - he was subsequently deemed not out [3] the only such decision in the history of Test cricket)

*/
